package servlet;

import bean.User;
import service.UserRegisterlmpl;
import service.UserServiceImpl;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

public class Register extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {

        try {
            //        请求参数中文乱码
            req.setCharacterEncoding("UTF-8");
//        使用参数名获得一个值
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            System.out.println(username + "  " + password);
//        封装到实体对象中。
            User user = new User();
            user.setUserName(username);
            user.setPassword(password);

//            调用业务层处理数据
            UserRegisterlmpl userRegisterlmpl = new UserRegisterlmpl();

            List existUser = userRegisterlmpl.register(user);
            System.out.println(existUser);
//            4.根据处理结果显示信息（页面跳转）
            if(existUser.size() == 0 ){
//                调用业务层添加数据
                int add = userRegisterlmpl.add(user);
                if (add == 0){
                    resp.getWriter().println("fail to register..1");
                }else {
//                注册成功
                resp.getWriter().println("registered successfully...");
                }
            }else {
//                该用户名已经存在，请输入其它用户名
                resp.getWriter().println("fail to register..");
            }

        }catch(Exception e){
            e.printStackTrace();
        }


        String hobbies = req.getParameter("hobby");
        System.out.println(Arrays.toString(new String[]{hobbies}));

        System.out.println("----------------");

        Map<String, String[]> allData = req.getParameterMap();
        for (Map.Entry<String, String[]> entry : allData.entrySet()) {
            System.out.print(entry.getKey());
            System.out.print("-->");
            System.out.println(Arrays.toString(entry.getValue()));
        }

        System.out.println("get请求响应");
    }


    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
        doGet(req, resp);
    }
}

